package com.xoa.service.task.impl;


import com.xoa.dao.task.TaskManageMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.task.TaskManage;
import com.xoa.model.users.Users;
import com.xoa.service.task.TaskAnalysisService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class TaskAnalysisServiceImpl<main> implements TaskAnalysisService {

    @Resource
    private TaskManageMapper taskManageMapper;

    @Resource
    private UsersMapper usersMapper;


    @Override
    public ToJson queryAnalysisReport(HttpServletRequest request) {
        ToJson toJson = new ToJson();
        try{
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            JSONObject object = new JSONObject();
            List list = new ArrayList();
            Map<String,Object>resultMap = new HashMap<>();
            Map<String,Object> map = new HashMap<>();
            map.put("userId",users.getUserId());
            List<TaskManage>taskManages =new ArrayList<>();
            taskManages = taskManageMapper.queryAnalysisReport(map);
            //任务总数
            resultMap.put("taskResultNumber",taskManages.size());
            //已完成
            map.put("taskStatus","1");
            taskManages = taskManageMapper.queryAnalysisReport(map);
            resultMap.put("completed",taskManages.size());
            //进行中
            map.put("taskStatus","0");
            taskManages = taskManageMapper.queryAnalysisReport(map);
            resultMap.put("processing",taskManages.size());
            //已延期
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String endDate = sdf.format(date);
            Map mapT = new HashMap();
            mapT.put("endDate",endDate);
            mapT.put("userId",users.getUserId());
            taskManages = taskManageMapper.queryAnalysisReport(mapT);
            resultMap.put("Postponed",taskManages.size());
            list.add(resultMap);
            toJson.setObj(list);
            toJson.setFlag(0);
            toJson.setMsg("success");
        }catch (Exception e){
            toJson.setFlag(1);
            toJson.setMsg("erro");
            e.printStackTrace();
        }
        return toJson;
    }

    @Override
    public ToJson queryPieTask(HttpServletRequest request) {
        ToJson toJson = new ToJson();
        try{
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            List list = new ArrayList();
            List<TaskManage>taskManages =new ArrayList<>();
            Map<String,Object>resultMap = new HashMap<>();
            Map<String,Object> map = new HashMap<>();
            map.put("userId",users.getUserId());
            //已完成
            map.put("taskStatus","1");
            taskManages = taskManageMapper.queryAnalysisReport(map);
            resultMap.put("completed",taskManages.size());
            //进行中
            map.put("taskStatus","0");
            taskManages = taskManageMapper.queryAnalysisReport(map);
            resultMap.put("processing",taskManages.size());
            list.add(resultMap);
            toJson.setObj(list);
            toJson.setFlag(0);
            toJson.setMsg("success");
        }catch (Exception e){
            toJson.setFlag(1);
            toJson.setMsg("erro");
            e.printStackTrace();
        }
        return toJson;
    }

    @Override
    public ToJson queryAnalysisTask(HttpServletRequest request, int type,Integer pageSize, Integer page, Boolean useFlag) {
        ToJson toJson = new ToJson();
        try{
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            JSONObject object = new JSONObject();
            List list = new ArrayList();
            Map<String,Object>resultMap = new HashMap<>();
            Map<String,Object> map = new HashMap<>();
            map.put("userId",users.getUserId());
            PageParams pages = new PageParams();
            pages.setPage(page);
            pages.setPageSize(pageSize);
            pages.setUseFlag(true);
            map.put("page", pages);
            List<TaskManage>taskManages =new ArrayList<>();
            switch (type) {
                case 1://任务总数
                    taskManages = taskManageMapper.queryAnalysisReport(map);
                    break;
                case 2://已完成
                    map.put("taskStatus","1");
                    taskManages = taskManageMapper.queryAnalysisReport(map);
                    break;
                case 3://进行中
                    map.put("taskStatus","0");
                    taskManages = taskManageMapper.queryAnalysisReport(map);
                    break;
                default://已延期
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String endDate = sdf.format(date);
                    map.put("endDate",endDate);
                    taskManages = taskManageMapper.queryAnalysisReport(map);
                    break;
            }
            for(TaskManage taskManage:taskManages){
                taskManage.setManageUserName(usersMapper.findUsersByuserId(taskManage.getManageUser()).getUserName());
            }
            toJson.setFlag(0);
            toJson.setMsg("success");
            toJson.setObj(taskManages);
            toJson.setTotleNum(pages.getTotal());
        }catch (Exception e){
            toJson.setFlag(1);
            toJson.setMsg("erro");
            e.printStackTrace();
        }
        return toJson;
    }

    @Override
    public ToJson queryTrendTask(HttpServletRequest request, String startDate) {
        ToJson toJson = new ToJson();
        try{
            Map<String,Object> mapResult = new HashMap<>();
            List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();

            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String createDate = sdf.format(date);
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            //新增（关于我的任务）
            Map<String,Object> map = new HashMap<>();
            map.put("userId",users.getUserId());

            List times = new ArrayList<>();
            Map<String,Object> mapInsertList = new HashMap<>();
            List insertList = new ArrayList();
            String[] createTime = new String[7];
            createTime[0] = startDate;
            createTime[1] = getNowDate(1,startDate);
            createTime[2] = getNowDate(1, createTime[1]);
            createTime[3] = getNowDate(1, createTime[2]);
            createTime[4] = getNowDate(1, createTime[3]);
            createTime[5] = getNowDate(1, createTime[4]);
            createTime[6] = getNowDate(1, createTime[5]);
            for(int i =0;i<createTime.length;i++){
                map.put("createDate",createTime[i]);
                insertList.add(taskManageMapper.queryTrendInsertTask(map).size());
                times.add(createTime[i]);
            }
            mapInsertList.put("name","新增任务");
            mapInsertList.put("data",insertList);
            data.add(mapInsertList);

        //完成任务
            Map<String,Object> mapCompList = new HashMap<>();
            List completeList = new ArrayList();
            for(int i =0;i<createTime.length;i++){
                map.put("completeDate",createTime[i]);// int compTaskCount = taskManageMapper.queryTrendCompTask(map);
                completeList.add(taskManageMapper.queryTrendInsertTask(map).size());
            }
            mapCompList.put("name","完成任务");
            mapCompList.put("data",completeList);
            data.add(mapCompList);
        //剩余任务
            Map<String,Object> mapRemainingList = new HashMap<>();
            mapRemainingList.put("userId",users.getUserId());
            List remainingList = new ArrayList();
            for(int i =0;i<createTime.length;i++){
                mapRemainingList.put("remainingDate", createTime[i]);//int remainingTaskCount = taskManageMapper.queryTrendRemainingTask(map);
                remainingList.add(taskManageMapper.queryTrendInsertTask(mapRemainingList).size());
            }
            mapRemainingList.put("name","剩余任务");
            mapRemainingList.put("data",remainingList);
            data.add(mapRemainingList);

            mapResult.put("data",data) ;
            mapResult.put("times",times);
            List list = new ArrayList();
            list.add(mapResult);
            toJson.setObj(list);
            toJson.setMsg("success");
            toJson.setFlag(0);
        }catch (Exception e){
            toJson.setFlag(1);
            toJson.setMsg("erro");
            e.printStackTrace();
        }
        return toJson;
    }


    public static String getNowDate(int i ,String specifiedDay) {
        if(i ==0){
            return specifiedDay;
        }
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day + 1);
        String dayBefore = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return dayBefore;
    }



}
